package com.chuangke.common.utils;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import cn.hutool.crypto.symmetric.AES;


public class AESUtil {
    /***
     * key和iv值需要和前端一致
     */
    public static final String KEY = "dfiowfensfshhaid";

    public static final String IV = "uyendmvjsgskgskh";

    public static void main(String[] args) {
        AES aes = new AES("CBC", "PKCS7Padding",
                KEY.getBytes(),
                IV.getBytes());

        String content = "123456";
        // 加密为16进制表示
        String encryptHex = aes.encryptHex(content);
        // 解密
        String decryptStr = aes.decryptStr(encryptHex);
        System.out.println(decryptStr);
    }

    public static String desEncrypt(String data) {
//        AES aes = new AES("CBC", "NoPadding",
//                KEY.getBytes(StandardCharsets.UTF_8),
//                IV.getBytes(StandardCharsets.UTF_8));
//        return aes.decryptStr(data) ;
        try {
            byte[] encrypted1 = new Base64().decode(data);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original).trim();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String encrypt(String content) {
        try {
            //对密码进行编码
            byte[] bytes = KEY.getBytes(StandardCharsets.UTF_8);
            //设置加密算法，生成秘钥
            SecretKeySpec skeySpec = new SecretKeySpec(bytes, "AES");
            // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            //偏移
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
            //选择加密
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            //根据待加密内容生成字节数组
            byte[] vv = content.getBytes() ;
            byte[] encrypted = cipher.doFinal(vv);
            //返回base64字符串
            return new Base64().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
